package com.xhldtc.login;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class BaiduTieba
{
	public static void main(String[] args)
	{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://tieba.baidu.com/f/commit/post/add");

		Map<String, String> params = new HashMap<String, String>();
		String cookie = getTieBaCookie(params);

		// post.addHeader("Referer", "http://tieba.baidu.com/p/2275186607");
		// post.addHeader("Host", "tieba.baidu.com");
		post.addHeader("Cookie", cookie);

		List<NameValuePair> list = new ArrayList<NameValuePair>();

		for (String s : params.keySet())
		{
			list.add(new BasicNameValuePair(s, params.get(s)));
		}

		// list.add(new BasicNameValuePair("lp_type", "0"));
		// list.add(new BasicNameValuePair("lp_sub_type", "0"));
		list.add(new BasicNameValuePair("content", "同菜的飘过。。"));

		// list.add(new BasicNameValuePair(
		// "mouse_pwd",
		// "52,50,62,43,48,53,54,55,14,54,43,55,43,54,43,55,43,54,43,55,43,54,43,55,43,54,43,55,14,53,54,53,51,62,63,14,54,52,49,49,43,48,49,63,13714680158071"));
		// list.add(new BasicNameValuePair("mouse_pwd_t", "1371468015807"));
		// list.add(new BasicNameValuePair("mouse_pwd_isclick", "1"));
		// list.add(new BasicNameValuePair("anonymous", "0"));
		// list.add(new BasicNameValuePair("tag", "11"));
		// list.add(new BasicNameValuePair("new_vcode", "1"));

		HttpResponse res = null;
		try
		{
			post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
			res = client.execute(post);
			System.out.println(EntityUtils.toString(res.getEntity(), "utf-8"));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

	}

	public static String getTieBaCookie(Map<String, String> params)
	{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet("http://tieba.baidu.com/p/2150187092");

		String cookie = getLoginCookie();
		get.addHeader("Cookie", cookie);

		HttpResponse res = null;
		try
		{
			res = client.execute(get);
//
//			File file = new File("result.html");
//			res.getEntity().writeTo(new FileOutputStream(file));
//
//			System.out.println("write success!");

			String s = EntityUtils.toString(res.getEntity(), "utf-8");

			Pattern patten = Pattern.compile("'tbs'  : \"(.+)\"");
			Matcher mat = patten.matcher(s);

			if (mat.find())
			{
				params.put("tbs", mat.group(1));
			}

			patten = Pattern
					.compile("kw:'([^']+)',ie:'([^']+)',rich_text:'([^']+)',floor_num:'([^']+)',fid:'([^']+)',tid:'([^']+)'");

			mat = patten.matcher(s);

			if (mat.find())
			{
				params.put("kw", mat.group(1));
				params.put("ie", mat.group(2));
				params.put("rich_text", mat.group(3));
				params.put("floor_num", mat.group(4));
				params.put("fid", mat.group(5));
				params.put("tid", mat.group(6));
			}

		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		StringBuilder sb = new StringBuilder(cookie);
		for (Cookie c : client.getCookieStore().getCookies())
		{
			sb.append("; ").append(c.getName()).append("=")
					.append(c.getValue());
		}

		return sb.toString();
	}

	public static String getLoginCookie()
	{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("https://passport.baidu.com/v2/api/?login");

		String[] array = getCookieAndToken();
		post.addHeader("Cookie", array[0]);

		List<NameValuePair> list = new ArrayList<NameValuePair>();

		list.add(new BasicNameValuePair("token", array[1]));
		list.add(new BasicNameValuePair("tpl", "pp"));

		list.add(new BasicNameValuePair("username", "xhldtc"));
		list.add(new BasicNameValuePair("password", "620701433"));

		try
		{
			post.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
			client.execute(post);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		StringBuilder sb = new StringBuilder(array[0]);
		for (Cookie c : client.getCookieStore().getCookies())
		{
			sb.append("; ").append(c.getName()).append("=")
					.append(c.getValue());
		}
		return sb.toString();
	}

	public static String[] getCookieAndToken()
	{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(
				"https://passport.baidu.com/v2/api/?getapi&tpl=pp&apiver=v3&class=login&callback=bd__cbs__g5yaw9&tt="
						+ System.currentTimeMillis());
		String cookie = getFirstCookie();

		get.addHeader("Cookie", cookie);

		HttpResponse response = null;
		String token = null;
		try
		{
			response = client.execute(get);
			String result = EntityUtils.toString(response.getEntity(), "UTF-8");

			int index = result.indexOf("token");
			int start = result.indexOf("\"", index + 8);
			int end = result.indexOf("\"", start + 1);
			token = result.substring(start + 1, end);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		for (Cookie c : client.getCookieStore().getCookies())
		{
			cookie += "; " + c.getName() + "=" + c.getValue();
		}
		return new String[] { cookie, token };
	}

	public static String getFirstCookie()
	{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet("https://passport.baidu.com/v2/?login");

		try
		{
			client.execute(get);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		StringBuilder sb = new StringBuilder();
		for (Cookie c : client.getCookieStore().getCookies())
		{
			sb.append("; ").append(c.getName()).append("=")
					.append(c.getValue());
		}
		return sb.substring(2);

	}
}

// PageData.thread = {
// author:"阿宸だ",
// id:2275186607,
// title:"水。。", reply_num:569, thread_type:"0",
// topic:{"is_topic":false,"topic_type":false,"is_live_post":false,"is_lpost":false,"lpost_type":0},
// is_ad:0, video_url:"" };
//
// PageData.thread.first_reply_time = '1366214343';